import pandas as pd
from lxml import etree
def generate_driving_machine_from_csv(path, name):
    csv_data = pd.read_csv(path, usecols = ['Time', 'Winkel', 'Speed2D'], skiprows=range(1, 5))
    time = csv_data['Time'].tolist()[0::10]
    swa = csv_data['Winkel'].tolist()[0::10]
    print(csv_data['Speed2D'][0])
    speed = csv_data['Speed2D'].mean()
    end_time = time[-1]
    swa_string = " ".join(list(str(x) for x in swa))
    time_string = " ".join(list(str(x) for x in time))

    
    root=etree.parse(r'.\template.xml').getroot()
    driving_machine_node = root[2][2][1][5]

    initial_speed_node = root[2][2]
    time_node = root[2][2][1][0][0]
    steering_swa_node = root[2][2][1][0][1]
    end_time_node = root[2][2][1]


    initial_speed_node.set("initialSpeed",str(speed))
    driving_machine_node.set("velocity",str(speed))
    end_time_node.set("abortTime",str(end_time))
    time_node.text = time_string
    steering_swa_node.text = swa_string

    etree.ElementTree(root).write(name, pretty_print = True)


csv_file_list = ["fr.csv","hg.csv","oc.csv","pse.csv"]

#generate_driving_machine_from_csv(r"W_01.MDF.csv", "test.xml")

for file in csv_file_list:
    print(file)
    path = "./csv/" + file
    name = "./" + file + ".xml"
    generate_driving_machine_from_csv(path, name)
